/*
 * 消息采用json传递
 * json有两种格式:
 * Message, Presence
 * Message: 用于两个用户之间发送信息
 * {'tag':'Nessage', 'type':'text', 'to':'lddfg', 'body':'Hello'}
 * Presence:
 * {'
 */

#include "connect.h"
#include "getmessages.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pgsql/libpq-fe.h>
char lasttime[64] = "";
char fristtime[64] = "";
int getmessages(char* ret, int ID){
    extern PGconn *conn;
	if(!conn) conn = dbconnect(); // 获取数据库连接标识
	char command[1024];
	sprintf(command, "select fromid, content, date from messages where toid=%d and status=true order by date;", ID);
	PGresult *res;
	res = PQexec(conn, command);
	if(PQresultStatus(res) != PGRES_TUPLES_OK){
		fprintf(stderr, "get错误!\t%s\t%s\n", PQerrorMessage(conn), command);
		PQclear(res);
		return 1;
	}
	sprintf(ret,"[");;
	int i = PQntuples(res), t = PQnfields(res);
	for(int s = 0; s < i; s++){
		sprintf(ret, "%s{\"from\":%s, \"content\":\"%s\", \"date\":\"%s\"}", ret, PQgetvalue(res, s, 0), PQgetvalue(res, s, 1), PQgetvalue(res, s, 2));
		if(s < i - 1)	sprintf(ret, "%s, ", ret);
	}
	if(i > 0){
		sprintf(fristtime, "%s", lasttime);
		sprintf(lasttime, "%s", PQgetvalue(res, i - 1, t - 1));
	}
	sprintf(ret,"%s]", ret);
	PQclear(res);
	return 0;
}
